/**
 * 1.还可下多少订单
 * 2.是不是休市.
 * 3.用户有多少钱.
 * 4.用户的赢家券.
 */
define('pages/order/create/refresh',['pages/index/model','util'],function(cfg,util) {
	var isShow=true,
	    timer,
	    groupid,
	    goodsCode,
	    refresh,
	    quotation,
	    setLastPrice=function(newQuotation){
	    	var id;
	    	for(id in cfg.lastPrice){
	    	   if(!quotation||newQuotation[id].close!=quotation[id].close){
	    	   		cfg.lastPrice[id] =!quotation?newQuotation[id].close:quotation[id].close;
	    	   }
	    	}			
		};
    return {
    	lastShowPrice:0,//
        init:function(cfgGroupid,code){
        	var fn=arguments.callee;
        	if(!refresh){
        	    refresh=this;
        	}
        	if(cfgGroupid){
        		groupid=cfgGroupid;
        		goodsCode=code;
        		isShow=true;
        	}
        	$.ajax({
		        url: util.url('hq'),
		        dataType: 'json',
		        success: function(data) {
		            //行情
		        	setLastPrice(data.quotes);
		        	quotation=data.quotes;
		        	
		            refresh.updateCurrentPrice();
		            if(isShow)timer=setTimeout(fn,cfg.refreshtime);
		        },
		        error: function() {
		            if(isShow)timer=setTimeout(fn, cfg.refreshtime);
		        }
		    });
        },
        updateCurrentPrice:function(){
        	var currentPrice=quotation[groupid].close,
        	    goods=cfg.goods_arr[goodsCode],
        	    mindecimal=goods.mindecimal,
		        lastPrice=cfg.lastPrice[groupid],
		        $currentPriceCt=$('#currentPrice'),
		        isUp,
		        removeCls,
		        priceFormat,
		        addCls;
		        
            if(this.lastShowPrice!=currentPrice&&$currentPriceCt.length){
            	priceFormat=mindecimal?(currentPrice/Math.pow(10,mindecimal)).toFixed(mindecimal):currentPrice;
            	isUp=currentPrice>=lastPrice;
	            removeCls=isUp?'down':'up';
                addCls=!isUp?'down':'up';
	            $currentPriceCt.html(priceFormat+(isUp?'↑':'↓')).removeClass(removeCls).addClass(addCls);
	            this.lastShowPrice=currentPrice;
            }
        },
        clearTimer:function(){
            clearTimeout(timer);
            isShow=false;
        }
    }
});


define('pages/order/stopPercent',[],function(){
	var step=10;
    return {
       obj:{
       	   up:0,
       	   down:0
       },
       setTicket:function(num,key){
       	   var $ct=$('#stopCt_'+key),
       	      val=this.obj[key];
       	      
       	   if((val==50&&num>0)||(val==0&&num<0))return;
       	   
       	   this.obj[key]=val+num*step;
       	   $ct.html(this.obj[key]+'%');
       },
       setInput:function(){
          $('#slpercent').val(this.obj.down);
          $('#tppercent').val(this.obj.up);
       },
       init:function(){
       	 var that=this;
          $('.stopPercentBtn').on('click',function(){
              var $this=$(this),
                  step=$this.data('step'),
                  direct=$this.data('direct');
              that.setTicket(+step,direct);
          })
       }
    }
});
define('pages/order/create/order',['util','pages/order/stopPercent','api'],function(util,stopPercent,api){
	var amount,
	    balance,
	    goods,
	    coupon;
	function   accAdd(arg1, arg2) {

    var r1, r2, m, c;

    try {

        r1 = arg1.toString().split(".")[1].length;

    }

    catch (e) {

        r1 = 0;

    }

    try {

        r2 = arg2.toString().split(".")[1].length;

    }

    catch (e) {

        r2 = 0;

    }

    c = Math.abs(r1 - r2);

    m = Math.pow(10, Math.max(r1, r2));

    if (c > 0) {

        var cm = Math.pow(10, c);

        if (r1 > r2) {

            arg1 = Number(arg1.toString().replace(".", ""));

            arg2 = Number(arg2.toString().replace(".", "")) * cm;

        } else {

            arg1 = Number(arg1.toString().replace(".", "")) * cm;

            arg2 = Number(arg2.toString().replace(".", ""));

        }

    } else {

        arg1 = Number(arg1.toString().replace(".", ""));

        arg2 = Number(arg2.toString().replace(".", ""));

    }

    return (arg1 + arg2) / m;

};
   	return {
		upDateUI:function(){
	        var $totalPrice=$('#total-price>b'),
	            $subBtn=$("#subBtn"),
		        $toCharge=$("#toCharge"),
		        orderamount = amount.getNumber(),
	            allfacevalue = coupon.getTotal(),
	            opencharge = goods.opencharge,
	            goodsprice = goods.goodsprice,
	            charge = opencharge * orderamount,
	            isTocharge;
	        //使用卷
	        if (allfacevalue > 0) {
	        	isTocharge = allfacevalue < goodsprice * orderamount;
	        } else {
	           isTocharge = accAdd(goodsprice * orderamount, charge) > balance;
	        }
	        $subBtn[isTocharge?'hide':'show']();
	        $toCharge[isTocharge?'show':'hide']();
	        
	        if (allfacevalue == 0) {
	            $totalPrice.html(accAdd(goodsprice * orderamount, charge).toFixed(2));
	        }else{
	        	$totalPrice.html('0.00')
	        }
	    },
	    init:function(cfg){
	    	goods=cfg.goods;
	    	amount=cfg.amount;
	    	coupon=cfg.coupon;
	    	this.events();
	    },
	    events:function(){
	       $("#orderForm").submit(function () {
		        var $this = $(this),
		            $subBtn = $('#subBtn'),
		        	postData;
		        	
		        try{	
			        coupon.setInput();
			        stopPercent.setInput();
			        postData= $this.serialize();
			        
			        api.createOrder({
			            data:postData,
			            cb:function (rtn) {
			                if (rtn.retcode == '0') {
                                            util.msg('建仓成功！');
			                     setTimeout(function(){location.hash='#/order';},500);
			                }else{ 
			                	 //20161209zyx:增加提示信息
			                	 util.dealErrorCode(rtn.retcode); 
			                	 $subBtn.removeAttr("disabled");
			                }
			            },
			            beforeSend: function () {
			            	$subBtn.attr('disabled',true);
			            }
			        });
		        }catch(e){
		        }
		        return false;
		    });  
	    }
   	}
})
define('pages/order/create/amount',['pages/index/model'],function(){
	var currentAmount;
	return {
		getNumber:function(){
		     return currentAmount;		
		},
		init:function(rows,stepamount,goods,order){
			var $numberSelected=$('#numberSelect'),			    
			    $orderamount=$('#orderamount'),
			    row;
			//建仓数字范围选择
			currentAmount=rows[0].min;
		    $('#rowSelecte').on('click','td',function () {
		        var $this=$(this),
		            index = $this.attr('data'),
		            row=rows[index],
		            count=1,
		            html='';
		         
		        for(var i=row.min;i<=row.max;i++){
		        	html+=['<li ',i==currentAmount?'class="selected"':'','>',i*stepamount,'</li>'].join('');
		        	count++;
		        }
		        
		        $this.siblings('.selected').removeClass('selected');
		        $this.addClass('selected');
		        
		        $numberSelected.html(html);
		    });
		    //建仓数字选择
		    $numberSelected.on('click','li',function () {
		        var $this=$(this),
		            orderamount =$this.html(),
		        	goodsprice = goods.goodsprice;
		            
		        $this.siblings().removeClass('selected');
		        $this.addClass('selected');
		        currentAmount=orderamount;
		        $orderamount.val(orderamount);
		        
		        $("#goodsprice>b").html(goodsprice * orderamount);
		        order.upDateUI();      
		    });
		}
	}
});
define(['jquery','api','user','tmpl','pages/index/model','text!pages/order/create.html','pages/order/create/refresh','pages/order/create/amount','pages/order/create/order','pages/order/coupon','pages/order/stopPercent'],function($,api,user,tmpl,model,text,refresh,amount,order,coupon,stopPercent){
	var view,
	    goods,
	    rows,
        maxperamount,
        stepamount,
        localdirect,
        userfunds,
        coupons=[];
	var controller={
	   init:function (goodscode,direct) {
	       var that=this,
	           data;

	       if(!user.checkLogin())return;
	       if(model.code==null){
	   	   		data=api.getGoods();
	   	   		if(!data||(data.errorcode&&data.errorcode!=0)||data.retcode!='0')return;
	   	   		model.addGoods(data);
	       }
	       localdirect=direct;
	       goods=model.goods_arr[goodscode];
	       refresh.init(goods.groupid,goodscode);
	       this.createRows(goods.maxperamount);
	       
	       stepamount=goods.stepamount;
	       api.userInfo(function(rs){
	    	    if(rs.retcode==='0'){
	    	    	userfunds=rs.userfund;
	    	        if(rs.couponsize!=0){
	    	        	controller.loadcoupons(function(){that.render()});
	    	        }
	    	        that.render();
	    	    }
	    	});
	       
	      
	    },
	    loadcoupons:function(cb){
	    	api.coupons(function(rs){
	    	    if(rs.retcode==='0'){
	    	    	if(rs.data){
	    	    	    coupons=rs.data;
	    	    	}else{
	    	    		coupons=[];
	    	    	}
	    	        cb();
	    	    }
	    	});
	    },
	    createRows:function(max){
	    	var min,
	    	    localmax;
	    	if(max<=10){
	    	   rows=[{
	    	      max:max,
	    	      min:1
	    	   }]
	    	}else if(max<=20){
	    	   rows=[{
	    	   	  max:10,
	    	      min:1
	    	   },{
	    	      max:max,
	    	      min:11
	    	   }]
	    	}else if(max<=30){
	    	   rows=[{
	    	   	  max:10,
	    	      min:1
	    	   },{
	    	      max:20,
	    	      min:11
	    	   },{
	    	      max:max,
	    	      min:21
	    	   }]
	    	}else{
	    	  	min = 1;
	    	  	rows=[];
				for(var i = 1; i <= 3; i ++) {
					localmax = min +(max / 3);
					rows [rows.length] = {
						'min':min,
						'max':i == 3 ? localmax : max 
					};
					min = localmax + 1;
				}
	    	}
	    },
	    render:function(){
	       var str;
	       view=$('#page');

	       str=tmpl(text,{rows:rows,goods:goods,coupons:coupons,stepamount:stepamount,direct:localdirect,userfunds:userfunds,lastPrice:refresh.lastPrice});
           view.html(str);
           this.events();
	    },
	    events:function(){
	       amount.init(rows,stepamount,goods,order);
	       coupon.init(order);
	       stopPercent.init();
	       order.init({goods:goods,amount:amount,balance:userfunds.balance,coupon:coupon});
	    },
        onRouteChange:function(){
	    	if(view)view.html('');
	    	refresh.clearTimer();
	    }
	}
    return controller;     
})